package org.xbl.xchain.sdk.gateway.init.xchain;

import com.moandjiezana.toml.TomlWriter;
import lombok.Data;
import org.xbl.xchain.sdk.utils.XcdUtil;

import java.lang.reflect.InvocationTargetException;
import java.time.Duration;
import java.util.HashMap;
@Data
public class XchainConfigToml {
    private String chainId;
    private String node;
    private String keyringBackend;
    private Duration trustPeriod;
    private int quorum;

    public XchainConfigToml(String chain_id, String node, String keyring_backend, Duration trust_period, int quorum) {
        this.chainId = chain_id;
        this.node = node;
        this.keyringBackend = keyring_backend;
        this.trustPeriod = trust_period;
        this.quorum = quorum;
    }

    public XchainConfigToml(String chain_id, String node){
        if (chain_id.equals("")){
            chain_id="xchain";
        }
        if (node.equals("")){
            node="tcp://localhost:26657";
        }
        this.node = node;
        this.chainId = chain_id;
        this.keyringBackend="test";
        this.quorum=2;
        this.trustPeriod=Duration.ofHours(200);
    }

    public String getTrustPeriod() {
        long seca = this.trustPeriod.toNanos()/1000000000;
        return (seca/60/60)+"h"+(seca/60%60)+"m"+seca%60+"s";
    }

    public void setTrustPeriod(String trustPeriod) {
        int h=trustPeriod.indexOf("h");
        int m=trustPeriod.indexOf("m");
        int s=trustPeriod.indexOf("s");
        Duration hour=Duration.ofHours(0);
        Duration mun=Duration.ofMinutes(0);
        Duration sec=Duration.ofMillis(0);
        if (h>=0){
            hour=Duration.ofHours(Integer.parseInt(trustPeriod.substring(0,h)));
        }
        if (m>=0){
            mun=Duration.ofMinutes(Integer.parseInt(trustPeriod.substring(Math.max(h+1, 0),m)));
        }
        if  (s>=0){
            sec=Duration.ofMillis(1000L *Integer.parseInt(trustPeriod.substring(Math.max(m+1, 0),s)));
        }

        this.trustPeriod = hour.plus(mun).plus(sec);
    }

    public String toTomlString() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        TomlWriter tomlWriter = new TomlWriter();
        return tomlWriter.write(XcdUtil.ConvertObj2Map(new HashMap<String,Object>(),this, XcdUtil.UNDERLINE));
    }

}
